# Create your views here.
from django.conf import settings
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.core.files import File
from django.db.models import signals
#from tvapi.settings import *
from urllib2 import urlopen, URLError
from urllib import urlretrieve
from tvapi.thetvdb.models import *
from tvapi.thetvdb.thetvdbxmlmodels import *

from pprint import pprint
import zipfile, cStringIO, os

import PIL
from PIL import Image
import os

def ImportLanguages(request):
    print 'Importing Languages'
    
    print settings.THETVDB_LANGUAGES_URL
    XML = urlopen(settings.THETVDB_LANGUAGES_URL).read()
    #pprint(XML)
    lan = LanguagesXML.fromXml(XML)
    #pprint(lan.Languages.toDict())
    for language in lan.Languages:
        pprint(language.toDict())
        #print language.name, language.abbreviation
        try:
            l = Language.objects.get(id=language.id)
            print 'Language Already Exists! %s' % l.name
            pprint(language.toDict())
        except Language.DoesNotExist as e:
            print e
            l = Language(id=language.id, abbreviation=language.abbreviation, name=language.name)
            l.save()
            
    raise Http404

import time
def ImportSeries(request, seriesid=None):
    print 'Initializing Image Types'
    InitializeImageTypes()
    print 'Importing Series: ' + seriesid
    url = settings.THETVDB_SERIES_URL_BASE + seriesid + '/all/en.zip'
    print url
    remotezip = urlopen(url)
    zipinmemory = cStringIO.StringIO(remotezip.read())
    zf = zipfile.ZipFile(zipinmemory)
    pprint(zf.namelist())
    XML = zf.read("en.xml")
    #pprint(XML)
    # Import Series Data
    fullSeries = SeriesFull.fromXml(XML)
    #pprint(fullSeries.Series.toDict())
    try:
        s = Series.objects.get(id=fullSeries.Series.id)
        pprint( 'Series Already Exists! %s' % s.SeriesName )
        pprint(s.__dict__)
    except Series.DoesNotExist as e:
        pprint( "Series Doesn't Exist! %s" % fullSeries.Series.SeriesName )
        s = Series()
        ConvertSeriesXMLToDB(fullSeries.Series, s)
        s.save()
        pprint(s.__dict__)
	ProcessGenres(fullSeries.Series, s)
#    if s.banner != None:
#        print "Series Banner Image Start"
#        if s.banner.image_file != None:
#            s.banner.image_file.delete()
#        urlimage = GetImageFromUrl(settings.THETVDB_IMAGE_URL_BASE+s.banner.image_path)
#        filename = os.path.basename(s.banner.image_path)
#        s.banner.image_file.save(filename, File(open(urlimage[0])))
#        print "%s - %s" % (s.banner.image_file.name, s.banner.image_file.path)
#        print "URL: %s" % s.banner.image_file.url
#        print "Series Banner Image End"
        #DownloadImage(settings.THETVDB_IMAGE_URL_BASE+s.banner.image_path, settings.THETVDB_BANNERS_ROOT+s.banner.image_path)
#    if s.fanart != None:
#        print "Series fanart Image Start"
#        if s.fanart.image_file != None:
#            s.fanart.image_file.delete()
#        urlimage = GetImageFromUrl(settings.THETVDB_IMAGE_URL_BASE+s.fanart.image_path)
#        filename = os.path.basename(s.fanart.image_path)
#        s.fanart.image_file.save(filename, File(open(urlimage[0])))
#        print "%s - %s" % (s.fanart.image_file.name, s.fanart.image_file.path)
#        print "URL: %s" % s.fanart.image_file.url
#        print "Series fanart Image End"
         #DownloadImage(settings.THETVDB_IMAGE_URL_BASE+s.fanart.image_path, settings.THETVDB_BANNERS_ROOT+s.fanart.image_path)
#    if s.poster != None:
#        print "Series poster Image Start"
#        if s.poster.image_file != None:
#            s.poster.image_file.delete()
#        urlimage = GetImageFromUrl(settings.THETVDB_IMAGE_URL_BASE+s.poster.image_path)
#        filename = os.path.basename(s.poster.image_path)
#        s.poster.image_file.save(filename, File(open(urlimage[0])))
#        print "%s - %s" % (s.poster.image_file.name, s.poster.image_file.path)
#        print "URL: %s" % s.poster.image_file.url
#        print "Series poster Image End"
        #DownloadImage(settings.THETVDB_IMAGE_URL_BASE+s.poster.image_path, settings.THETVDB_BANNERS_ROOT+s.poster.image_path)
    
    # Import All Episodes
    extra_actors_time = 0
    for episode in fullSeries.Episodes:
        try:
            e = Episodes.objects.get(id=episode.id)
            pprint( 'Episode Already Exists! %s' % e.EpisodeName )
        except Episodes.DoesNotExist as err:
            pprint( "Episode Doesn\'t Exist! %s" % episode.EpisodeName )
            e = Episodes()
            ConvertEpisodeXMLToDB(episode, e, s)
            e.save()
            ProcessGuestStars(episode, e)
            ProcessDirectors(episode, e)
            ProcessWriters(episode, e)
            #season = Season(id=e.seasonid, series=s, season_number=e.SeasonNumber)
#            season = Season()
#            season.id = e.seasonid
#            season.series = s
#            season.season_number = e.SeasonNumber
#            season.save()
            
#        if e.filename != None:
#            print "Episode filename Image Start"
#            if e.filename.image_file != None:
#                e.filename.image_file.delete()
#            urlimage = GetImageFromUrl(settings.THETVDB_IMAGE_URL_BASE+e.filename.image_path)
#            filename = os.path.basename(e.filename.image_path)
#            e.filename.image_file.save(filename, File(open(urlimage[0])))
#            print "%s - %s" % (e.filename.image_file.name, e.filename.image_file.path)
#            print "URL: %s" % e.filename.image_file.url
#            print "Episode filename Image End"
            #DownloadImage(settings.THETVDB_IMAGE_URL_BASE+e.filename.image_path, settings.THETVDB_BANNERS_ROOT+e.filename.image_path)
    
    # Import Actors
    actorsXML = ActorsXML.fromXml(zf.read("actors.xml"))
    for actor in actorsXML.Actors:
        try:
            a = Actor.objects.get(name=actor.Name)
            ar = ActorRoles.objects.get(series=s, actor=a)
            pprint( 'Actor Already Exists! %s' % a.name )
        except Actor.DoesNotExist:
            pprint( "Actor Doesn't Exist! %s" % actor.Name )
            a = Actor()
            ar = ActorRoles()
        except ActorRoles.DoesNotExist:
            ar = ActorRoles()
        ConvertActorXMLToDB(actor, a, ar, s)
        a.save()
        ar.actor = a
        ar.series = s
        ar.save()
    
#        if a.image != None:
#            print "Actor Image Start"
#            if a.image.image_file != None:
#                a.image.image_file.delete()
#            urlimage = GetImageFromUrl(settings.THETVDB_IMAGE_URL_BASE+a.image.image_path)
#            filename = os.path.basename(a.image.image_path)
#            a.image.image_file.save(filename, File(open(urlimage[0])))
#            print "%s - %s" % (a.image.image_file.name, a.image.image_file.path)
#            print "URL: %s" % a.image.image_file.url
#            print "Actor Image End"
            #DownloadImage(settings.THETVDB_IMAGE_URL_BASE+a.image.image_path, settings.THETVDB_BANNERS_ROOT+a.image.image_path)
            
    # Import Banners
#    bannersXML = BannersXML.fromXml(zf.read("banners.xml"))
#    #print bannersXML
#    for banner in bannersXML.Banners:
#        try:
#            b = Banners.objects.get(BannerPath=banner.BannerPath)
#            print 'Banner Already Exists! ' + banner.id
#        except Banners.DoesNotExist as e:
#            print "Banner Doesn't Exist! " + banner.id
#            b = Banners()
#            b.series = s
#            ConvertBannerXMLToDB(banner, b)
#            b.save()
#        
#        if banner.BannerPath != None:
#            DownloadImage(settings.THETVDB_IMAGE_URL_BASE+banner.BannerPath, settings.THETVDB_BANNERS_ROOT+banner.BannerPath)
#        if banner.ThumbnailPath != None:
#            DownloadImage(settings.THETVDB_IMAGE_URL_BASE+banner.ThumbnailPath, settings.THETVDB_BANNERS_ROOT+banner.ThumbnailPath)
#        else:
#            GenerateThumbnail(settings.THETVDB_BANNERS_ROOT+banner.BannerPath, settings.THETVDB_BANNERS_ROOT+'_cache/'+banner.BannerPath)
#            b = Banners.objects.get(id=banner.id)
#            b.ThumbnailPath = '_cache/'+banner.BannerPath
#            b.save()
#        if banner.VignettePath != None:
#            DownloadImage(settings.THETVDB_IMAGE_URL_BASE+banner.VignettePath, settings.THETVDB_BANNERS_ROOT+banner.VignettePath)
        
    # Close out the zip file.
    zf.close()
    
#    raise Http404
    return HttpResponse("Ok")

def ImportEpisode(request, seriesid=None, language='en', season=None, episode=None):
    print 'Importing Episode! ' + episode
    
    url = THETVDB_SERIES_URL_BASE + seriesid + '/default/' + season + '/' + episode + '/' + language + '.xml'
    print url
    XML = urlopen(url).read()
    print(XML)
    episodeData = EpisodeData.fromXml(XML)
    pprint(episodeData.Episode.toDict())
    try:
        e = Episodes.objects.get(id=episodeData.Episode.id)
        print 'Episode Already Exists! ' + e.EpisodeName
    except Episodes.DoesNotExist as err:
        print "Episode Doesn't Exist! " + episodeData.Episode.EpisodeName
        e = Episodes()
        ConvertEpisodeXMLToDB(episodeData.Episode, e)
        e.save()
        
#    raise Http404
    return HttpResponse("Ok")
    
def ConvertSeriesXMLToDB(seriesXML, seriesDB):
    #pprint(vars(seriesXML))
    #pprint(vars(seriesDB))
    seriesDB.id = seriesXML.id
    seriesDB.Actors = seriesXML.Actors
    seriesDB.Airs_DayOfWeek = seriesXML.Airs_DayOfWeek
    seriesDB.Airs_Time = seriesXML.Airs_Time
    seriesDB.ContentRating = seriesXML.ContentRating
    seriesDB.FirstAired = seriesXML.FirstAired
    seriesDB.Genre = seriesXML.Genre
    seriesDB.IMDB_ID = seriesXML.IMDB_ID
    seriesDB.language = Language.objects.get(abbreviation=seriesXML.Language)
    seriesDB.Network = seriesXML.Network
    seriesDB.Overview = seriesXML.Overview
    seriesDB.Rating = seriesXML.Rating
    seriesDB.Runtime = seriesXML.Runtime
    seriesDB.SeriesID = seriesXML.SeriesID
    seriesDB.SeriesName = seriesXML.SeriesName
    seriesDB.Status = seriesXML.Status
#    seriesDB.banner = seriesXML.banner
    if seriesXML.banner != None:
        try:
            i = ImageDB.objects.get(image_path=seriesXML.banner)
        except ImageDB.DoesNotExist:
            it = ImageType.objects.get(name="banner")
            i = ImageDB()
            i.image_type = it
            i.language = seriesDB.language
            i.image_path = seriesXML.banner
            i.save()
        seriesDB.banner = i
#    seriesDB.fanart = seriesXML.fanart
    if seriesXML.fanart != None:
        try:
            i = ImageDB.objects.get(image_path=seriesXML.fanart)
        except ImageDB.DoesNotExist:
            it = ImageType.objects.get(name="fanart")
            i = ImageDB(image_type=it, language=seriesDB.language, image_path=seriesXML.fanart)
            i.save()
        seriesDB.fanart = i
    seriesDB.lastupdated = seriesXML.lastupdated
    seriesDB.zap2it_id = seriesXML.zap2it_id
#    seriesDB.poster = seriesXML.poster
    if seriesXML.poster != None:
        try:
            i = ImageDB.objects.get(image_path=seriesXML.poster)
        except ImageDB.DoesNotExist:
            it = ImageType.objects.get(name="poster")
            i = ImageDB(image_type=it, language=seriesDB.language, image_path=seriesXML.poster)
            i.save()
        seriesDB.poster = i
        
    pprint(seriesDB.__dict__)
    
def ConvertEpisodeXMLToDB(episodeXML, episodeDB, seriesDB):
    
    try:
        s = Season.objects.get(id=episodeXML.seasonid)
        print "Season found!"
    except:
        print "Season not found! %s" % episodeXML.seasonid
        s = Season()
        s.id = episodeXML.seasonid
        s.series = seriesDB
        s.season_number = episodeXML.SeasonNumber
        s.save()
        
    episodeDB.id = episodeXML.id
    episodeDB.season = s
#    episodeDB.seasonid = episodeXML.seasonid
    episodeDB.EpisodeNumber = episodeXML.EpisodeNumber
    if episodeXML.EpisodeName != None:
        episodeDB.EpisodeName = episodeXML.EpisodeName
    episodeDB.FirstAired = episodeXML.FirstAired
#    episodeDB.GuestStars = episodeXML.GuestStars
#    episodeDB.Director = episodeXML.Director
#    episodeDB.Writer = episodeXML.Writer
    episodeDB.Overview = episodeXML.Overview
    episodeDB.ProductionCode = episodeXML.ProductionCode
    episodeDB.lastupdated = episodeXML.lastupdated
    episodeDB.flagged = episodeXML.flagged
    episodeDB.DVD_discid = episodeXML.DVD_discid
    episodeDB.DVD_season = episodeXML.DVD_season
    episodeDB.DVD_episodenumber = episodeXML.DVD_episodenumber
    episodeDB.DVD_chapter = episodeXML.DVD_chapter
    episodeDB.absolute_number = episodeXML.absolute_number
    if episodeXML.filename != None:
        try:
            i = ImageDB.objects.get(image_path=episodeXML.filename)
        except ImageDB.DoesNotExist:
            it = ImageType.objects.get(name="episode")
            i = ImageDB(image_type=it, language=Language.objects.get(abbreviation=episodeXML.Language), image_path=episodeXML.filename)
            i.save()
#    episodeDB.filename = episodeXML.filename
        episodeDB.filename = i
    episodeDB.mirrorupdate = episodeXML.mirrorupdate
    episodeDB.IMDB_ID = episodeXML.IMDB_ID
    episodeDB.EpImgFlag = episodeXML.EpImgFlag
    episodeDB.Rating = episodeXML.Rating
#    episodeDB.SeasonNumber = episodeXML.SeasonNumber
    episodeDB.language = Language.objects.get(abbreviation=episodeXML.Language)
    episodeDB.series = Series.objects.get(id=episodeXML.seriesid)

    pprint(episodeDB.__dict__)
    
def ConvertActorXMLToDB(actorXML, actorDB, actorRoleDB, seriesDB):
    actorDB.name = actorXML.Name
#    actorDB.Image = actorXML.Image
    if (actorXML.Image != None) and (actorDB.image == None):
        it = ImageType.objects.get(name="actor")
        i = ImageDB(image_type=it, language=seriesDB.language, image_path=actorXML.Image)
        i.save()
        actorDB.image = i
    elif (actorXML.Image != None) and (actorDB.image != None):
        actorDB.image.image_path = actorXML.Image
        
    actorRoleDB.Role = actorXML.Role
    actorRoleDB.SortOrder = actorXML.SortOrder
    actorRoleDB.thetvdbid = actorXML.id
#    actorDB.id = actorXML.id
#    actorDB.Image = actorXML.Image
#    actorDB.Name = actorXML.Name
#    actorDB.Role = actorXML.Role
#    actorDB.SortOrder = actorXML.SortOrder
    
    pprint(actorDB.__dict__)
    
def ConvertBannerXMLToDB(bannerXML, bannerDB):
    bannerDB.id = bannerXML.id
    #bannerDB.Series = 
    bannerDB.BannerPath = bannerXML.BannerPath
    bannerDB.BannerType = bannerXML.BannerType
    bannerDB.BannerType2 = bannerXML.BannerType2
    bannerDB.Colors = bannerXML.Colors
    if (bannerXML.Language != "") and (bannerXML.Language != None):
        bannerDB.language = Language.objects.get(abbreviation=bannerXML.Language)
    else:
        bannerDB.language = Language.objects.get(abbreviation="en")
    bannerDB.ThumbnailPath = bannerXML.ThumbnailPath
    bannerDB.VignettePath = bannerXML.VignettePath
    
    pprint(bannerDB.__dict__)

def GetImageFromUrl(url):
    try:
        if url != None:
            webFile = urlretrieve(url)
    except IOError, e:
        webFile = ""
        print e
        
    return webFile

def DownloadImage(url, outfile):
    print url, outfile
    try:
        if not os.path.exists(outfile):
            (filepath, filename) = os.path.split(outfile)
            if not os.path.exists(filepath):
                os.makedirs(filepath)
        webFile = urlopen(url)
        localFile = open(outfile, 'wb')
        localFile.write(webFile.read())
        webFile.close()
        localFile.close()
        GenerateThumbnail(outfile)
    except IOError as e:
        print e

def GenerateThumbnail(origImage, outfile=None, thumbSize=settings.THETVDB_DEFAULT_MAX_THUMBNAIL_SIZE):
    try:
        if outfile != None:
            if not os.path.exists(outfile):
                (filepath, filename) = os.path.split(outfile)
                if not os.path.exists(filepath):
                    os.makedirs(filepath)
        img = Image.open(origImage)
        img.thumbnail(thumbSize, Image.ANTIALIAS)
        if outfile != None:
            img.save(outfile, "JPEG")
            print 'Created Thumbnail: ' + outfile
        else:
            img.save(origImage, "JPEG")
            print 'Created Thumbnail: ' + origImage
    except IOError as e:
        print e
        
def InitializeImageTypes():
    try:
        it = ImageType()
        it.name="fanart"
        it.save()
        pprint(it)
        it = ImageType()
        it.name="poster"
        it.save()
        pprint(it)
        it = ImageType()
        it.name="banner"
        it.save()
        pprint(it)
        it = ImageType()
        it.name="series"
        it.save()
        pprint(it)
        it = ImageType()
        it.name="episode"
        it.save()
        pprint(it)
        it = ImageType()
        it.name="season"
        it.save()
        pprint(it)
        it = ImageType()
        it.name="thumbnail"
        it.save()
        pprint(it)
        it = ImageType()
        it.name="vignette"
        it.save()
        pprint(it)
        it = ImageType()
        it.name="actor"
        it.save()
        pprint(it)
        
        return True
    except Exception as e:
        pprint(e)
        return False
    
def ProcessGuestStars(episodeXML, episodeDB):
    if (episodeXML.GuestStars != None):
        for stars in episodeXML.GuestStars.split("|"):
            if stars.strip() != "":
                try:
                    g = GuestStar.objects.get(name=stars.strip())
                    #g = episodeDB.gueststars.objects.get(name=stars)
                    #eg = episodeDB.gueststars.get(g)
                except GuestStar.DoesNotExist:
                    g = GuestStar(name=stars.strip())
                    g.save()
                
                try:
                    eg = episodeDB.gueststars.get(name=g.name)
                except GuestStar.DoesNotExist:
                    episodeDB.gueststars.add(g)
                    
        episodeDB.save()
        
def ProcessDirectors(episodeXML, episodeDB):
    if (episodeXML.Director != None):
        for director in episodeXML.Director.split("|"):
            if director.strip() != "":
                try:
                    d = Director.objects.get(name=director)
                except Director.DoesNotExist, e:
                    d = Director(name=director)
                    d.save()
                episodeDB.directors.add(d)
        episodeDB.save()

def ProcessWriters(episodeXML, episodeDB):
    if (episodeXML.Writer != None):
        for writer in episodeXML.Writer.split("|"):
            if writer.strip() != "":
                try:
                    w = Writer.objects.get(name=writer)
                except Writer.DoesNotExist, e:
                    w = Writer(name=writer)
                    w.save()
                episodeDB.writers.add(w)
        episodeDB.save()

def ProcessGenres(seriesXML, seriesDB):
    if seriesXML.Genre != None:
        for genre in seriesXML.Genre.split("|"):
            if genre.strip() != "":
                try:
                    g = Genre.objects.get(name=genre)
                except Genre.DoesNotExist, e:
                    g = Genre(name=genre)
                    g.save()
                seriesDB.genres.add(g)
        seriesDB.save()

#def do_auto_thumbnail_save(sender, instance, created, *args, **kwargs):
#    """
#    Create a Thumbnail out of every image to make them faster for mobile apps.
#    """
#    print "do_auto_thumbnail_save Start"
#    try:
#        if instance.image_file != None:
#            GenerateThumbnail(instance.image_file.path)
#    except IOError, e:
#        print e
#    print "do_auto_thumbnail_save End"
#
#signals.post_save.connect(do_auto_thumbnail_save, sender=ImageDB)
